//封装axios
import Vue from 'vue'
import axios from 'axios'
import { Message,Loading} from 'element-ui'
import router from './router'



axios.defaults.timeout =5000;                        //响应时间
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';        //配置请求头
axios.defaults.baseURL = '/';   //配置接口地址
let loading;//初始化loading
//开始加载动画
function startLoading() {
    loading = Loading.service({
        lock: true,
        text:'拼命加载中...'
    })
}
//结束加载动画
function endLoading() {
    loading.close();
}

//请求拦截 设置统一header
axios.interceptors.request.use(
    config =>{
        //加载
        if(config.headers.isloading == false){
            endLoading();
        }else{
        startLoading();
    }
        config.headers['token'] = localStorage.getItem('token') // 请求头带上token
        return config;
    
    },
    error =>{
        return Promise.reject(error);
    }
);

//相应拦截
axios.interceptors.response.use(
    response =>{
        endLoading();
        return response.data;
    },
    error =>{
        //错误提醒
        endLoading();

        //清除token
        localStorage.removeItem('toekn');
        return Promise.reject(error);
    }
);


export default axios;
